package cn.smartaccount.demo.common.util;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author xuluquan
 * @date 2021-07-09 19:46
 */
public class CommonUtil {

    private static Logger logger = LoggerFactory.getLogger(CommonUtil.class);

    public static Map<String, Object> getFieldNameValue(Object obj) {

        Field[] fields = obj.getClass().getDeclaredFields();
        Map<String, Object> map = Maps.newHashMap();
        for (Field field : fields) {
            String name = field.getName();
            try {
                field.setAccessible(true);
                Object value = field.get(obj);
                map.put(name, value);
            } catch (Exception e) {
                logger.error("获取属性名称和属性值异常", e);
            }
        }
        return map;
    }

    public static String renderTemplate(String content, Map<String, Object> map) {
        if (StringUtils.isBlank(content)) {
            return StringUtils.EMPTY;
        }
        Set<Map.Entry<String, Object>> sets = map.entrySet();
        for (Map.Entry<String, Object> entry : sets) {
            String regex = "\\$\\{" + entry.getKey() + "}";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(content);
            content = matcher.replaceAll(entry.getValue() == null ? "" : entry.getValue().toString());
        }
        return content;
    }



}
